package demo.android.myapplication.demos.views

import android.content.Context
import android.graphics.*
import android.os.Build
import android.util.AttributeSet
import android.view.View
import androidx.annotation.RequiresApi
import cn.android.basic.*
import demo.android.myapplication.R

/**
 * <br>createBy Gw
 * <br>createTime: 2021/7/8 15:46
 */
class MultiLineTextView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        textSize = 16.sp
    }

    private val img:Bitmap = decodeResource(resources, R.mipmap.ic_launcher_copy, 80.dp.int)
    private val fm = Paint.FontMetrics()
    private val rectF = RectF()
    private val rect = Rect()

    private var text:String =
        "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        rectF.set(width - img.width.float, 80.dp, width.float, 80.dp + img.height)
        rect.set(0, 0, img.width, img.height)
        canvas.drawBitmap(img, rect, rectF, paint)

        val fontSpacing = paint.getFontMetrics(fm)
        var offsetY = -fm.top
        var start = 0
        val fontHeight = fm.bottom - fm.top
        while (start < text.length) {
            val fontTop = offsetY + fm.top
            val right = if(fontTop + fontHeight >= rectF.top && fontTop <= rectF.bottom){
                width - img.width.float
            }else{
                width.float
            }
            val count = paint.breakText(text, start, text.length, true, right, null)
            canvas.drawText(text, start, start + count, 0f, offsetY, paint)
            offsetY += fontSpacing
            start += count
        }
    }
}